package com.huawen.cms.app.service;

import com.huawen.cms.app.dto.CategoryTree;
import com.huawen.cms.app.entity.Category;
import com.huawen.cms.app.mapper.ArticleMapper;
import com.huawen.cms.app.mapper.BaseMapper;
import com.huawen.cms.app.mapper.CategoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CategoryServiceImpl extends BaseServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper mapper;

    @Override
    public BaseMapper getMapper() {
        return mapper;
    }


    public CategoryTree getTree(Integer id, Integer dep) {

        CategoryTree tree = new CategoryTree();

        Category mod = (Category) getById(id);
        if (mod == null) {
            return tree;
        }

        // dep==1 child取一下
        if (dep == 1) {
            tree = ConvertToTree(mod);

            Category filter = new Category();
            filter.setpId(id);
            filter.setDataFlag(1);
            List<Category> list = getList(filter);
            if (list != null && list.size() > 0) {
                tree.setChildren(ConvertToTreeList(list));
            }

        } else {
            //默认只返回自己
            tree = ConvertToTree(mod);
        }

        return tree;
    }

    public CategoryTree getTreeDep(Integer id) {
        CategoryTree tree = new CategoryTree();
        Category mod = (Category) getById(id);
        tree = ConvertToTree(mod);
        return tree;
    }

    public CategoryTree ConvertToTree(Category category) {
        CategoryTree tree = new CategoryTree();
        tree.setId(category.getId());
        tree.setArtId(category.getArtId());
        tree.setDataFlag(category.getDataFlag());
        tree.setLevel(category.getLevel());
        tree.setName(category.getName());
        tree.setpId(category.getpId());
        return tree;
    }

    public List<CategoryTree> ConvertToTreeList(List<Category> list) {

        List<CategoryTree> retrunList = new ArrayList<>();

        for (Category item : list) {
            CategoryTree tree = new CategoryTree();
            tree.setId(item.getId());
            tree.setArtId(item.getArtId());
            tree.setDataFlag(item.getDataFlag());
            tree.setLevel(item.getLevel());
            tree.setName(item.getName());
            tree.setpId(item.getpId());
            retrunList.add(tree);
        }
        return retrunList;
    }

}
